package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.sys.core.properties.WxXcxConfig;
import cn.stylefeng.guns.sys.modular.system.model.params.wxacodeunlimitParam;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


/**
 * 控制器
 *
 * @author jiangge
 * @Date 2021-07-26 13:21:06
 */
@Controller
@RequestMapping("/wxXcxApi")
public class WxXcxApiController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(WxXcxApiController.class);

    @Autowired
    private WxXcxConfig wxXcxConfig;

    /**
     * 获取小程序分享码图片Buffer
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, path = "/getWxacodeunLimit")
    @ResponseBody
    public ResponseData accessToken(@RequestBody wxacodeunlimitParam param) {
        if (StringUtils.isBlank(param.getScene())) {
            return ResponseData.error(412, "请求失败,scene参数不可为空");
        }

        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxXcxConfig.getAppid() + "&secret=" + wxXcxConfig.getSecret();
        String content = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(content);
        String accessToken = jsonObject.get("access_token").toString();


        JSONObject json = new JSONObject();
        json.put("scene", param.getScene());
        if (StringUtils.isNotBlank(param.getPage())) {
            json.put("page", param.getPage());
        }
        if (param.getWidth() != null) {
            json.put("width", param.getWidth());
        } else {
            json.put("width", 430);
        }
        if (param.getAuto_color() != null) {
            json.put("auto_color", param.getAuto_color());
        } else {
            json.put("auto_color", false);
        }
        if (param.getLine_color() != null) {
            json.put("line_color", param.getLine_color());
        }
        if (param.getIs_hyaline() != null) {
            json.put("is_hyaline", param.getIs_hyaline());
        } else {
            json.put("is_hyaline", false);
        }


        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
        String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        String result = restTemplate.postForEntity(codeUrl, formEntity, String.class).getBody();
        System.out.println("result:" + result);

        return ResponseData.success(result);
    }


    /**
     * 获取小程序分享码图片Buffer转化的base64码 HttpPost方式
     *
     * @param param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, path = "/getwxacodeunlimit")
    @ResponseBody
    public ResponseData getwxacodeunlimit(@RequestBody wxacodeunlimitParam param) {
        logger.info("群通知-生成小程序分享码请求参数：{}", param.toString());
        try {
            //获取accessToken
            if (StringUtils.isBlank(param.getScene())) {
                return ResponseData.error(412, "请求失败,scene参数不可为空");
            }

            RestTemplate restTemplate = new RestTemplate();
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxXcxConfig.getAppid() + "&secret=" + wxXcxConfig.getSecret();
            String content = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(content);
            String accessToken = jsonObject.get("access_token").toString();

            Map<String, Object> params = new HashMap<>();
            params.put("scene", param.getScene());
            if (StringUtils.isNotBlank(param.getPage())) {
                params.put("page", param.getPage());
            }
            if (param.getWidth() != null) {
                params.put("width", param.getWidth());
            } else {
                params.put("width", 430);
            }
            if (param.getAuto_color() != null) {
                params.put("auto_color", param.getAuto_color());
            } else {
                params.put("auto_color", false);
            }
            if (param.getLine_color() != null) {
                params.put("line_color", param.getLine_color());
            }
            if (param.getIs_hyaline() != null) {
                params.put("is_hyaline", param.getIs_hyaline());
            } else {
                params.put("is_hyaline", false);
            }

            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);  // 接口
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            String body = JSON.toJSONString(params);           //必须是json模式的 post
            StringEntity entity;
            entity = new StringEntity(body);
            entity.setContentType("image/png");

            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();
            // 将获取流转为base64格式
            String result = "";
            byte[] data = null;
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();

            result = new String(Base64.getEncoder().encode(data));
            return ResponseData.success(result);
        } catch (Exception e) {
            return ResponseData.error(412, "请求失败," + e.getMessage());
        }
    }


    /**
     * 获取小程序的分享码图片
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, path = "/getwxacodeunlimit2")
    @ResponseBody
    public ResponseData accessToken22(@RequestBody wxacodeunlimitParam param) {
        if (StringUtils.isBlank(param.getScene())) {
            return ResponseData.error(412, "请求失败,scene参数不可为空");
        }

        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxXcxConfig.getAppid() + "&secret=" + wxXcxConfig.getSecret();
        String content = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(content);
        String accessToken = jsonObject.get("access_token").toString();


        JSONObject json = new JSONObject();
        json.put("scene", param.getScene());
        if (StringUtils.isNotBlank(param.getPage())) {
            json.put("page", param.getPage());
        }
        if (param.getWidth() != null) {
            json.put("width", param.getWidth());
        } else {
            json.put("width", 430);
        }
        if (param.getAuto_color() != null) {
            json.put("auto_color", param.getAuto_color());
        } else {
            json.put("auto_color", false);
        }
        if (param.getLine_color() != null) {
            json.put("line_color", param.getLine_color());
        }
        if (param.getIs_hyaline() != null) {
            json.put("is_hyaline", param.getIs_hyaline());
        } else {
            json.put("is_hyaline", false);
        }


//        HttpHeaders headers = new HttpHeaders();
//        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//        headers.setContentType(type);
//        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//        HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
        String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
//        String result = restTemplate.postForEntity(codeUrl, formEntity, String.class).getBody();


        //设置头部
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        Map<String, String> requestBody = new HashMap<String, String>();
        requestBody.put("scene", param.getScene());
        requestBody.put("page", param.getPage());
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, requestHeaders);
        byte[] res = restTemplate.postForObject(codeUrl, requestEntity, byte[].class);


        //将获取到的buffer流存储到本地图片
        String path = "D:/pictureUpload/project/";
        String name = "test2.jpg";
        File f = new File(path + "test2.jpg");

        try {
            if (res.length <= 500) {//如果byte字节流小于500，说明返回的是err错误码而非buffer
                return ResponseData.error(412, "IO Error," + res);
            } else {
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(f));
                out.write(res);
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error(412, "IO Error," + e.getMessage());
        }
        return ResponseData.success(name);
    }

    /**
     * 获取小程序的分享码图片restTemplate方式
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, path = "/getwxacodeunlimit3")
    @ResponseBody
    public ResponseData accessToken23(@RequestBody wxacodeunlimitParam param) {
        try {
            if (StringUtils.isBlank(param.getScene())) {
                return ResponseData.error(412, "请求失败,scene参数不可为空");
            }

            RestTemplate restTemplate = new RestTemplate();
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxXcxConfig.getAppid() + "&secret=" + wxXcxConfig.getSecret();
            String content = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(content);
            String accessToken = jsonObject.get("access_token").toString();


            JSONObject json = new JSONObject();
            json.put("scene", param.getScene());
            if (StringUtils.isNotBlank(param.getPage())) {
                json.put("page", param.getPage());
            }
            if (param.getWidth() != null) {
                json.put("width", param.getWidth());
            } else {
                json.put("width", 430);
            }
            if (param.getAuto_color() != null) {
                json.put("auto_color", param.getAuto_color());
            } else {
                json.put("auto_color", false);
            }
            if (param.getLine_color() != null) {
                json.put("line_color", param.getLine_color());
            }
            if (param.getIs_hyaline() != null) {
                json.put("is_hyaline", param.getIs_hyaline());
            } else {
                json.put("is_hyaline", false);
            }

            String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;

            //设置头部
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_JSON);
            Map<String, String> requestBody = new HashMap<String, String>();
            requestBody.put("scene", param.getScene());
            requestBody.put("page", param.getPage());
            HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, requestHeaders);
            byte[] res = restTemplate.postForObject(codeUrl, requestEntity, byte[].class);

            if(res.length<500){
                String resStr=new String(res);
                JSONObject jo = JSON.parseObject(resStr);
                if (jo.get("errcode") != null) {
                    if (jo.get("errcode").toString().equals("45009")) {
                        return ResponseData.error(412, "调用分钟频率受限(目前5000次/分钟，会调整)，如需大量小程序码，建议预生成。");
                    }
                    if (jo.get("errcode").toString().equals("41030")) {
                        return ResponseData.error(412, "所传page页面不存在，或者小程序没有发布");
                    }
                    return ResponseData.error(412, "请求失败，+result");
                }
            }


            String result = Base64.getEncoder().encodeToString(res);
            return ResponseData.success(result);
        } catch (Exception e) {
            return ResponseData.error(412, "请求失败," + e.getMessage());
        }
    }

}



